package leetcode;

public class AddTwoNumbers02 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(9);
        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(9);
        l2.next.next = new ListNode(9);

        ListNode result = addTwoNumbers(l1, l2);
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode result = new ListNode();
        ListNode tempNode = result;
        int ex = 0;
        while (p1.next != null && p2.next != null) {
            tempNode.val = (p1.val + p2.val + ex) % 10;
            ex = (p1.val + p2.val + ex) / 10;
            p1 = p1.next;
            p2 = p2.next;
            tempNode.next = new ListNode();
            tempNode = tempNode.next;
        }
        tempNode.val = (p1.val + p2.val + ex) % 10;
        ex = (p1.val + p2.val + ex) / 10;
        p1 = p1.next;
        p2 = p2.next;

        while (p1!= null) {
            tempNode.next = new ListNode((p1.val + ex) % 10);
            ex = (p1.val + ex) / 10;
            p1 = p1.next;
            tempNode = tempNode.next;
        }
        while (p2!= null) {
            tempNode.next = new ListNode((p2.val + ex) % 10);
            ex = (p2.val + ex) / 10;
            p2 = p2.next;
            tempNode = tempNode.next;
        }
        if (ex != 0) {
            tempNode.next = new ListNode(ex);
        }
        return result;
    }
}


